import hashlib
import json
import random
import string
import time
import urllib
import redis

r = redis.Redis(host="127.0.0.1", port=6379)
appid = 'wxd3ee0ceae85cdb76'
sceret = '41b9f5dbd4bb3283a71cd5ef2cb9c729'

class Signs:
    def __init__(self,url):
        self.ret = {
            'nonceStr': self.__create_nonce_str(),
            'jsapi_ticket': self.__get_jsapi_ticket(),
            'timestamp': self.__create_timestamp(),
            'url':url
        }
    # 生成随机字符串nodeceStr
    def __create_nonce_str(self):
        nonceStr = ''.join(
            random.choice(string.ascii_letters + string.digits)
            for _ in range(15))
        print("nonceStr:" + nonceStr)
        return nonceStr  #创建随机字符串

    # 生成时间戳
    def __create_timestamp(self):
        timeSTAMP = int(time.time())
        print("timestamp:" + str(timeSTAMP))
        return timeSTAMP  # 创建一个时间戳

    def __get__token(self):
        #从redis中获取到的值为字节类型，需要转化为字符串类型str(ACCESS_TOKEN,encoding='utf-8')
        ACCESS_TOKEN = r.get("wx:ACCESS_TOKEN")
        if ACCESS_TOKEN is not None:
            return str(ACCESS_TOKEN, encoding='utf-8')
        else:
            try:
                token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}".format(
                    appid, sceret)  # 创建获取token的url
                response = urllib.request.urlopen(token_url)
                b = response.read().decode('utf-8')
                token = json.loads(b)

                ACCESS_TOKEN = token.get("access_token")

                r.set(
                    'wx:ACCESS_TOKEN',
                    ACCESS_TOKEN,
                    ex=7200,
                )  # 将获取到的 ACCESS_TOKEN 存入redis中并且设置过期时间为7200s

                return ACCESS_TOKEN
            except Exception as e:
                return e
    def __get_jsapi_ticket(self):
        #从redis中获取到的值为字节类型，需要转化为字符串类型str(ticket,encoding='utf-8')
        ticket = r.get("wx:ticket")
        if ticket is not None:
            tic = str(ticket, encoding='utf-8')
            return format(tic)
        else:
            try:
                token = self.__get__token()
                ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={}&type=jsapi".format(
                    token)

                get_ticket = urllib.request.urlopen(ticket_url)

                c = get_ticket.read().decode("utf-8")

                js_ticket = json.loads(c)

                ticket = js_ticket.get("ticket")

                r.set("wx:ticket", str(ticket), ex=7200)
                #r.setex('jsapi_ticket', ticket, 7200)
                print("获取到")
                return ticket
            except Exception as e:
                return e

    def __sign(self):
        string = '&'.join([
            '%s=%s' % (key.lower(), self.ret[key]) for key in sorted(self.ret)
        ])  # 根据字符的ASCII值进行排序，拼接
        print("string:" + string)
        self.ret['signature'] = hashlib.sha1(
            string.encode('utf-8')).hexdigest()  # 对字符串进行sha1加密
        return self.ret
   
    def config(self):
        
        results={"appid":appid,"result":self.__sign()}
        response_heade = {'Access-Control-Allow-Origin': '*'}
        result=results["result"]

        return result
